package com.pan.framework.tomcat;

import com.pan.framework.tomcat.entity.ServletInfo;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

import javax.servlet.http.HttpServlet;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MyTomcat {

    private Tomcat tomcat;

    public void resetTomcat(Tomcat tomcat){
        this.tomcat = tomcat;
    }

    public MyTomcat(){
        this(false);
    }
    public MyTomcat(boolean isResource){
        tomcat = new Tomcat();
        tomcat.setPort(80);
        tomcat.getConnector();

        if (isResource) {
            String projectPath = System.getProperty("user.dir") + "\\src\\main\\webapp";
            Context context = tomcat.addWebapp("", projectPath);
            WebResourceRoot resources = new StandardRoot(context);
            String classesPath = System.getProperty("user.dir") + "\\target\\classes";
            resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes", classesPath, "/"));
            context.setResources(resources);
        }
    }

    public void addServer(Collection<ServletInfo> servletInfos){
        servletInfos.stream()
//                .peek(System.out::println) //debug
                .filter(s->s!=null).forEach(this::addServer);
    }
    private Map<String,Context> contextMap = new HashMap<>();
    public void addServer(ServletInfo servletInfo){

        Context context = null;
        String contextPath = servletInfo.getControlPath();
        if (contextMap.containsKey(contextPath) ){
            context = contextMap.get(contextPath);
        }else {
            context = tomcat.addContext(contextPath,
                    new File(".").getAbsolutePath());
            contextMap.put(contextPath,context);
        }
        tomcat.addServlet(
                context,
                servletInfo.getServletName(),
                servletInfo.getServlet()
        );
        context.addServletMappingDecoded(
                servletInfo.getMethodPath(),
                servletInfo.getServletName()
        );
//        log :
//        System.out.println("注册servlet:");
//        System.out.println("context path: "+ contextPath);
//        System.out.println("pattern: " + servletInfo.getMethodPath());
//        System.out.println("servlet name: "+ servletInfo.getServletName());

    }


    public void run() throws LifecycleException {
        //第三部分
        tomcat.start();
        tomcat.getServer().await();
    }

    public void stop() throws LifecycleException {
        tomcat.stop();
    }
}
